package com.atguigu.juc.atomics;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yfstart
 * @create 2022-07-20 17:30
 */
public class AtomicIntegerDemo {
  public static final int SIZE = 50;

  public static void main(String[] args) throws InterruptedException {

    MyNumber myNumber = new MyNumber();
    CountDownLatch countDownLatch = new CountDownLatch(SIZE);

    for (int i = 0; i < SIZE; i++) {
      new Thread(()->{
        try {
          for(int j = 0; j < 1000; j++) {
            myNumber.addPlusPlus();
          }
        } finally {
          countDownLatch.countDown();
        }
      },String.valueOf(i)).start();
    }
    // 等待上面50个线程全部计算完成后，再去获得最终值

    /// 方式一：暂停几秒钟线程
    // try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace();}

    // 方式二：countDownLatch
    countDownLatch.await();

    System.out.println(Thread.currentThread().getName() + "\t result：" + myNumber.atomicInteger.get());
  }
}

class MyNumber {
  AtomicInteger atomicInteger = new AtomicInteger();

  public void addPlusPlus() {
    atomicInteger.getAndIncrement();
  }
}
